const taskForm = document.getElementById('taskForm');
const taskList = document.getElementById('taskList');

function formatDateTime(dt) {
  if (!dt) return '';
  const d = new Date(dt);
  return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')} ${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}`;
}

function formatDuration(start, end) {
  if (!start || !end) return '';
  const ms = new Date(end) - new Date(start);
  if (ms < 0) return '';
  const min = Math.round(ms / 60000);
  if (min < 60) {
    return `${Math.max(1, min)}min`;
  } else {
    const h = Math.floor(min / 60);
    const m = min % 60;
    if (m === 0) return `${h}h`;
    return `${h}h/${m}min`;
  }
}

function isToday(dateStr) {
  if (!dateStr) return false;
  const d = new Date(dateStr);
  const now = new Date();
  return d.getFullYear() === now.getFullYear() &&
    d.getMonth() === now.getMonth() &&
    d.getDate() === now.getDate();
}

function formatDurationFromSegments(timerSegments) {
  if (!Array.isArray(timerSegments) || timerSegments.length === 0) return '';
  let totalMs = 0;
  timerSegments.forEach(seg => {
    if (seg.start && seg.end) {
      totalMs += new Date(seg.end) - new Date(seg.start);
    }
  });
  let min = Math.floor(totalMs / 60000);
  let sec = Math.floor((totalMs % 60000) / 1000);
  if (min < 1) {
    return `${sec}s`;
  }
  if (min < 60) {
    return sec > 0 ? `${min}min/${sec}s` : `${min}min`;
  } else {
    const h = Math.floor(min / 60);
    const m = min % 60;
    if (sec > 0) {
      return m === 0 ? `${h}h/${sec}s` : `${h}h/${m}min/${sec}s`;
    }
    if (m === 0) return `${h}h`;
    return `${h}h/${m}min`;
  }
}

function renderTasks(tasks) {
  taskList.innerHTML = '';
  // 分组
  const pending = tasks.filter(t => t.status === '待处理');
  const inProgress = tasks.filter(t => t.status === '进行中');
  const todayCompleted = tasks.filter(t => t.status === '已完成' && isToday(t.completedAt));
  if (inProgress.length > 0) {
    const inProgressTitle = document.createElement('div');
    inProgressTitle.textContent = 'In Progress';
    inProgressTitle.style = 'font-size:13px;color:#1677ff;font-weight:600;margin:8px 0 2px 0;';
    taskList.appendChild(inProgressTitle);
    inProgress.forEach((task, idx) => renderTaskItem(task, idx, tasks));
  }
  if (pending.length > 0) {
    const pendingTitle = document.createElement('div');
    pendingTitle.textContent = 'Pending';
    pendingTitle.style = 'font-size:13px;color:#faad14;font-weight:600;margin:8px 0 2px 0;';
    taskList.appendChild(pendingTitle);
    pending.forEach((task, idx) => renderTaskItem(task, idx, tasks));
  }
  if (todayCompleted.length > 0) {
    const completedTitle = document.createElement('div');
    completedTitle.textContent = 'Done Today';
    completedTitle.style = 'font-size:13px;color:#52c41a;font-weight:600;margin:12px 0 2px 0;';
    taskList.appendChild(completedTitle);
    todayCompleted.forEach((task, idx) => renderTaskItem(task, idx, tasks));
  }
  if (pending.length === 0 && inProgress.length === 0 && todayCompleted.length === 0) {
    const empty = document.createElement('div');
    empty.textContent = 'No tasks to show.';
    empty.style = 'color:#aaa;text-align:center;margin:16px 0;';
    taskList.appendChild(empty);
  }
}

function renderTaskItem(task, idx, tasks) {
  const li = document.createElement('li');
  li.className = task.status === '已完成' ? 'completed' : '';
  let statusClass = 'task-status';
  if (task.status === '进行中') statusClass += ' in-progress';
  if (task.status === '待处理') statusClass += ' pending';
  let statusText = task.status;
  if (task.status === '进行中') statusText = 'In Progress';
  else if (task.status === '已完成') statusText = 'Done';
  else if (task.status === '待处理') statusText = 'Pending';
  let durationStr = '';
  if (task.status === '已完成' && Array.isArray(task.timerSegments)) {
    durationStr = `<span style='color:#faad14;font-size:12px;margin-left:8px;'>${formatDurationFromSegments(task.timerSegments)}</span>`;
  }
  // 不再渲染任何操作按钮
  let btnGroup = '';
  // 已完成任务主区只显示标题和状态
  if (task.status === '已完成') {
    li.innerHTML = `
      <div class="task-title">
        <span>${task.title}</span>
        <span style="display:flex;align-items:center;gap:4px;">
          ${durationStr}
          <span class="${statusClass}" style="min-width:64px;text-align:right;">${statusText}</span>
        </span>
      </div>
    `;
  } else {
    li.innerHTML = `
      <div class="task-title">
        <span>${task.title}</span>
        <span style="display:flex;align-items:center;gap:4px;">
          ${durationStr}
          <span class="${statusClass}" style="min-width:64px;text-align:right;">${statusText}</span>
        </span>
      </div>
      <div class="task-desc single-line">
        ${task.description ? task.description + '<br>' : ''}
        ${task.createdAt ? `<span style='color:#aaa;font-size:12px;'>Started: ${formatDateTime(task.createdAt)}</span>` : ''}
        ${task.status === '已完成' && task.completedAt ? `<br><span style='color:#aaa;font-size:12px;'>Completed: ${formatDateTime(task.completedAt)}</span>` : ''}
      </div>
    `;
  }
  // 已完成事项可点击展开/收起详情，详情内有按钮（这些按钮保留但不做任何操作）
  if (task.status === '已完成') {
    li.style.cursor = task.description ? 'pointer' : 'default';
    let descVisible = false;
    li.addEventListener('click', (e) => {
      if (e.target.tagName.toLowerCase() === 'button') return;
      descVisible = !descVisible;
      // 展开前先移除已有desc
      const oldDesc = li.querySelector('[data-desc="1"]');
      if (oldDesc) li.removeChild(oldDesc);
      if (descVisible) {
        const desc = document.createElement('div');
        desc.className = 'task-desc';
        desc.innerHTML =
          (task.description ? `<div style='margin-bottom:4px;'>${task.description}</div>` : '') +
          `<div style='color:#aaa;font-size:12px;margin-bottom:4px;'>Created: ${formatDateTime(task.createdAt)}<br>Completed: ${formatDateTime(task.completedAt)}</div>`;
        desc.style.marginTop = '4px';
        desc.setAttribute('data-desc', '1');
        li.appendChild(desc);
      }
    });
  }
  // 不再绑定任何操作按钮事件
  taskList.appendChild(li);
}

function loadTasks() {
  chrome.storage.local.get({tasks: []}, (result) => {
    renderTasks(result.tasks);
  });
}

taskForm.addEventListener('submit', (e) => {
  e.preventDefault();
  const titleInput = document.getElementById('title');
  const title = titleInput.value.trim();
  const description = document.getElementById('description').value.trim();
  const status = '待处理';
  const createdAt = '';
  if (!title) return;
  chrome.storage.local.get({tasks: []}, (result) => {
    const tasks = result.tasks;
    tasks.unshift({title, description, status, createdAt});
    chrome.storage.local.set({tasks}, loadTasks);
    taskForm.reset();
    titleInput.focus();
  });
});

document.addEventListener('DOMContentLoaded', () => {
  loadTasks();
  document.getElementById('title').focus();
});

document.getElementById('viewAllBtn').onclick = function() {
  window.open('all.html');
}; 